<?php
namespace Realisation\Bash;

use Model\Parser\ParserListInterface;
use Model\Parser\ParserOneInterface;
use Model\Parser\ParserException;
use Symfony\Component\DomCrawler\Crawler;

/**
 * Description of Parser
 *
 * @author pahhan
 */
class Parser implements ParserListInterface
{
    /**
     *
     * @var \Model\Parser\ParserOneInterface
     */
    protected $one_parser;

    function __construct(ParserOneInterface $one_parser)
    {
        $this->one_parser = $one_parser;
    }

    public function getMessages(Crawler $crawler)
    {
        $css = '#body div.quote';
        $messages = $crawler->filter($css)->reduce(function($node) {
            return (bool) $node->filter('div.text')->count();
        });
        if( !$messages->count() ) {
            throw new ParserException(sprintf('Cant find messages by "%s"', $css));
        }
        $one_parser = $this->one_parser;
        $out = $messages->each(function ($crawler, $i) use ($one_parser) {
            return $one_parser->getMessage($crawler);
        });

        return $out;
    }

    public function getNextPageUrl(Crawler $crawler, $current_page = NULL)
    {
        $css = 'div.pager form:first-child span.current+a';
        $a = $crawler->filter($css);
        if( !$a->count() ) {
            throw new ParserException(sprintf('Cant find url by "%s"', $css));
        }

        return $a->first()->link()->getUri();
    }
}